﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;

namespace windows_application
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Socket server;
        private Thread myThread;
        private Boolean doStopServer = false;

        public MainWindow()
        {
            InitializeComponent();

            const Int32 c_port = 2000;

            // Create a socket, bind it to the server's port, and listen for client 
            // connections.
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
            server.Bind(localEndPoint);
            server.Listen(Int32.MaxValue);
            
        }

        private void startServerBtn_Click(object sender, RoutedEventArgs e)
        {
            if(myThread == null)
            {
                myThread = new Thread(StartServer);
                myThread.Start();

                status.Text = "Started.";
                startServerBtn.Content = "Stop server";
            }

            else
            {
                stopServer();
                startServerBtn.Content = "Start server";
            }
        }

        private void stopServer()
        {
            doStopServer = true;
            myThread.Suspend();
            myThread = null;
            status.Text = "Stopped.";
        }

        private void StartServer()
        {
            doStopServer = false;
            while (!doStopServer)
            {
                // Wait for a client to connect.
                Socket clientSocket = server.Accept();

                // Process the client request.  true means asynchronous.
                new ProcessClientRequest(clientSocket, true);
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if(myThread != null && myThread.IsAlive)
                stopServer();
        }

        
    }
}
